package luanvan.app.foodnote;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;

import luanvan.app.foodnote.library.AlertDialogManager;
import luanvan.app.foodnote.library.GooglePlaces;
import luanvan.app.foodnote.library.JSONParser;
import luanvan.app.foodnote.library.Place;
import luanvan.app.foodnote.library.PlacesList;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;

public class GooglePlacesActivity extends SherlockActivity implements
		LocationListener {

	AlertDialogManager alert = new AlertDialogManager();
	private ProgressDialog pDialog;
	// Google Places
	GooglePlaces googlePlaces;

	// Places List
	PlacesList nearPlaces;

	JSONParser jsonParser = new JSONParser();

	// private static final String url_food_detials =
	// "http://10.0.2.2/foodnote/get_food_details.php";

	// private static final String url_food_detials =
	// "http://192.168.0.104/foodnote/get_food_details.php";
	// private static final String url_get_foods_around =
	// "http://demoluanvan.iblogger.org/get_foods_around.php";

	private double latExtra, lngExtra;
	private String reference, lat, lng;
	// Places Listview
	ListView lv;

	private static final String TAG_LATITUDE = "LATITUDE";
	private static final String TAG_LONGITUDE = "LONGITUDE";

	// ListItems data
	ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String, String>>();
	// KEY Strings
	private static String KEY_REFERENCE = "reference"; // id of the place
	private static String KEY_NAME = "name"; // name of the place
	private static String KEY_ICON = "icon";
	private static String KEY_LAT = "lat";
	private static String KEY_LNG = "lng";
	// private static String KEY_VICINITY = "vicinity"; // Place area name
	private static final int TEN_METERS = 10; // 10 meters
	private static final int TWO_MINUTES = 1000 * 60 * 2; // 2 minutes

	private LocationManager locationManager;
	private Location location;
	private String provider;
	private double getLat, getLng;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.googleplaces);

		getSupportActionBar().setIcon(R.drawable.food_around);
		getSupportActionBar().show();

		lv = (ListView) findViewById(R.id.list);

		Intent i = getIntent();
		latExtra = i.getExtras().getDouble(TAG_LATITUDE);
		lngExtra = i.getExtras().getDouble(TAG_LONGITUDE);

		if (latExtra != 0 && lngExtra != 0)
			new LoadPlaces().execute(latExtra, lngExtra);

		this.initLocation();

		registerForContextMenu(lv);

		lv.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> paretn, View view,
					int position, long id) {
				// getting values from selected ListItem

				lat = ((TextView) view.findViewById(R.id.latGooglePlace))
						.getText().toString();
				lng = ((TextView) view.findViewById(R.id.lngGooglePlace))
						.getText().toString();

				reference = ((TextView) view.findViewById(R.id.reference))
						.getText().toString();

				openContextMenu(view);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		checkGPS();
	}

	@Override
	protected void onResume() {
		super.onResume();
		locationManager.requestLocationUpdates(provider, TEN_METERS,
				TWO_MINUTES, this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		locationManager.removeUpdates(this);
	}

	private void initLocation() {
		// Get the location manager
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// Define the criteria how to select the locatioin provider -> use
		// default
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		provider = locationManager.getBestProvider(criteria, false);
		location = locationManager.getLastKnownLocation(provider);
		if (location != null) {
			System.out.println("Best Available provider " + provider
					+ " has been selected.");
			this.onLocationChanged(location);
			// locationManager.requestLocationUpdates(provider, TEN_METERS,
			// TWO_MINUTES, this);
			// Log.d("Location", String.valueOf(getLat) + ", " +
			// String.valueOf(getLng));
		} else {
			Log.d("Location", "No location");
		}
	}

	private boolean checkGPS() {
		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				1000L, 1.0f, (LocationListener) this);
		boolean isGPS = locationManager
				.isProviderEnabled(LocationManager.GPS_PROVIDER);
		return isGPS;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Tùy chọn");
		menu.setHeaderIcon(R.drawable.submenu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.google_places_ctx, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case R.id.detailsGooglePlace:

			Intent in = new Intent(getApplicationContext(),
					SinglePlaceActivity.class);
			in.putExtra(KEY_REFERENCE, reference);
			startActivity(in);
			return true;

		case R.id.directionGooglePlace:
			String dirMap = "http://maps.google.com/maps?";
			StringBuffer sBuf = new StringBuffer(dirMap);
			sBuf.append("saddr=");
			sBuf.append(getLat);
			sBuf.append(',');
			sBuf.append(getLng);
			sBuf.append("&daddr=");
			sBuf.append(Double.valueOf(lat));
			sBuf.append(',');
			sBuf.append(Double.valueOf(lng));
			Intent direction = new Intent(
					android.content.Intent.ACTION_VIEW, Uri.parse(sBuf
							.toString()));
			startActivity(direction);
			
			return true;

		}
		return (super.onOptionsItemSelected(item));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.google_place, menu);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
		switch (item.getItemId()) {
		case R.id.google_place:
			Intent maps_place = new Intent(this, LocationActivity.class);
			maps_place.putExtra(TAG_LATITUDE, Double.valueOf(latExtra));
			maps_place.putExtra(TAG_LONGITUDE, Double.valueOf(lngExtra));
			Log.d("Location Extra",
					String.valueOf(latExtra) + ", " + String.valueOf(lngExtra));
			startActivity(maps_place);
			return true;
		}
		return false;
	}

	private class LoadPlaces extends AsyncTask<Double, Void, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(GooglePlacesActivity.this);
			pDialog.setTitle("Xin chờ");
			pDialog.setMessage("Đang tải danh sách địa điểm...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected String doInBackground(Double... agrs) {
			double lat = agrs[0];
			double lng = agrs[1];

			googlePlaces = new GooglePlaces();
			try {
				String types = "cafe|food|restaurant";
				double radius = 1000; // 1 km
				nearPlaces = googlePlaces.search(lat, lng, radius, types);
				
				// updating UI from Background Thread
				runOnUiThread(new Runnable() {
					public void run() {
						/**
						 * Updating parsed Places into LISTVIEW
						 * */
						// Get json response status
						String status = nearPlaces.status;

						// Check for all possible status
						if (status.equals("OK")) {

							// Successfully got places details
							if (nearPlaces.results != null) {
								// loop through each place
								for (Place p : nearPlaces.results) {
									HashMap<String, String> map = new HashMap<String, String>();

									// Place reference won't display in listview -
									// it will be hidden
									// Place reference is used to get
									// "place full details"
									map.put(KEY_REFERENCE, p.reference);

									// Place name
									map.put(KEY_NAME, p.name);
									
									map.put(KEY_LAT, String.valueOf(p.geometry.location.lat));
									map.put(KEY_LNG, String.valueOf(p.geometry.location.lng));

									Log.d("LatLng", String.valueOf(p.geometry.location.lat) + ", " + String.valueOf(p.geometry.location.lng));
									map.put(KEY_ICON, p.icon);

									// adding HashMap to ArrayList
									placesListItems.add(map);
								}
/*
								for (int i = 0; i < placesListItems.size(); i++) {
									try {
										URL url = new URL(placesListItems.get(i)
												.get(KEY_ICON));
										try {
											Bitmap bmp = BitmapFactory
													.decodeStream(url
															.openConnection()
															.getInputStream());
											Log.d("ICON", bmp.toString());
										} catch (IOException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									} catch (MalformedURLException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}*/
								// list adapter
								ListAdapter adapter = new SimpleAdapter(
										GooglePlacesActivity.this, placesListItems,
										R.layout.list_item, new String[] {
												KEY_REFERENCE, KEY_LAT, KEY_LNG, KEY_NAME },
										new int[] { R.id.reference, R.id.latGooglePlace, R.id.lngGooglePlace, R.id.name });

								// Adding data into listview
								lv.setAdapter(adapter);
							}
						} else if (status.equals("ZERO_RESULTS")) {
							// Zero results found
							alert.showAlertDialog(GooglePlacesActivity.this,
									"Địa Điểm Xung Quanh",
									"Không có nơi nào được tìm thấy.", false);
							// startActivity(new Intent(GooglePlacesActivity.this,
							// AllFoodsActivity.class));
						} else if (status.equals("UNKNOWN_ERROR")) {
							alert.showAlertDialog(GooglePlacesActivity.this, "Lỗi",
									"Không biết lỗi xảy ra.", false);
							// startActivity(new Intent(GooglePlacesActivity.this,
							// AllFoodsActivity.class));
						} else if (status.equals("OVER_QUERY_LIMIT")) {
							alert.showAlertDialog(GooglePlacesActivity.this, "Lỗi",
									"Truy vấn tới Google Place bị giới hạn.", false);
							// startActivity(new Intent(GooglePlacesActivity.this,
							// AllFoodsActivity.class));
						} else if (status.equals("REQUEST_DENIED")) {
							alert.showAlertDialog(GooglePlacesActivity.this, "Lỗi",
									"Yêu cầu bị từ chối.", false);
							// startActivity(new Intent(GooglePlacesActivity.this,
							// AllFoodsActivity.class));
						} else if (status.equals("INVALID_REQUEST")) {
							alert.showAlertDialog(GooglePlacesActivity.this, "Lỗi",
									"Yêu cầu không hợp lệ.", false);
							// startActivity(new Intent(GooglePlacesActivity.this,
							// AllFoodsActivity.class));
						} else {
							alert.showAlertDialog(GooglePlacesActivity.this, "Lỗi",
									"Xin lỗi đã xảy ra lỗi.", false);
							// startActivity(new Intent(GooglePlacesActivity.this,
							// AllFoodsActivity.class));
						}
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}

			return null;
		}

		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			

		}
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		getLat = location.getLatitude();
		getLng = location.getLongitude();
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}
}
